package com.monster.config;

import com.monster.security.HealthUserDetailServiceImpl;
import com.monster.security.JWTAuthenticationFilter;
import com.monster.security.JWTAuthorizationFilter;
import com.monster.security.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 *    重写默认配置类  WebSecurityConfigurerAdapter
 *    configure (AuthenticationManagerBuilder auth)   重写默认的用户认证信息 参照源码 注释编写
 *
 *    request.getParameter()    HttpxxxxWrapper   包装类   MvcWebConfigure  json null
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //  开启权限注解
@EnableConfigurationProperties(JwtProperties.class)
public class HealthWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtProperties properties;

    @Autowired
    private HealthUserDetailServiceImpl healthUserDetailService;

    /**
     *  重写用户认证信息
     * @param auth
     * @throws Exception
     *
     * 密码加密 框架  PasswordEncoder  密码加密
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         //  数据库认证和授权配置
        auth.userDetailsService(healthUserDetailService).passwordEncoder(createPasswordEncoder());
    }

    @Bean
    public static PasswordEncoder  createPasswordEncoder(){
        return  new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().
                disable().
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session
    }

    public static void main(String[] args) {
        System.out.println(createPasswordEncoder().encode("123"));
    }
}



